import type { FormProps } from 'antd';
import { Button, Col, Form, Input, Row, message, Tooltip, Dropdown, Modal } from 'antd';
import style from './style.module.scss'
import { useNavigate } from 'react-router-dom';
import { reg } from '../../api/info';
import { useState, useRef, useEffect } from 'react';
import { LockOutlined, UserOutlined, EyeOutlined, EyeInvisibleOutlined, SafetyOutlined, ReloadOutlined, GlobalOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { MenuProps } from 'antd';
import CaptchaVerification from '../../compages/CaptchaVerification';

function Index() {
    const [captcha, setCaptcha] = useState<string>('')
    const [captchaInput, setCaptchaInput] = useState<string>('')
    const [passwordVisible, setPasswordVisible] = useState(false)
    const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const [captchaLoading, setCaptchaLoading] = useState(false)
    const [captchaModalVisible, setCaptchaModalVisible] = useState(false);
    const [pendingFormValues, setPendingFormValues] = useState<any>(null);
    const [form] = Form.useForm();
    const canvasRef = useRef<HTMLCanvasElement>(null)
    const nav = useNavigate()
    
    type FieldType = {
        username?: string;
        password?: string;
        confirmPassword?: string;
        captcha?: string;
    };

    const { t, i18n } = useTranslation();

    // 获取当前语言显示文本
    const getCurrentLanguageText = () => {
        switch (i18n.language) {
            case 'zh':
                return '🇨🇳 中文';
            case 'en':
                return '🇺🇸 English';
            case 'ko':
                return '🇰🇷 한국어';
            default:
                return '🇨🇳 中文';
        }
    };

    // 语言切换菜单
    const languageItems: MenuProps['items'] = [
        {
            key: 'zh',
            label: '中文',
            icon: '🇨🇳',
            onClick: () => {
                i18n.changeLanguage('zh');
                localStorage.setItem('language', 'zh');
            }
        },
        {
            key: 'en',
            label: 'English',
            icon: '🇺🇸',
            onClick: () => {
                i18n.changeLanguage('en');
                localStorage.setItem('language', 'en');
            }
        },
        {
            key: 'ko',
            label: '한국어',
            icon: '🇰🇷',
            onClick: () => {
                i18n.changeLanguage('ko');
                localStorage.setItem('language', 'ko');
            }
        }
    ];

    // 生成随机验证码
    const generateRandomCaptcha = (): string => {
        const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
        let result = '';
        for (let i = 0; i < 4; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    };

    // 绘制验证码图片
    const drawCaptcha = (text: string) => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        canvas.width = 120;
        canvas.height = 40;

        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 渐变背景
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, '#f8fafc');
        gradient.addColorStop(1, '#e2e8f0');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 添加轻微的干扰线
        for (let i = 0; i < 2; i++) {
            ctx.strokeStyle = `rgba(59, 130, 246, ${0.1 + Math.random() * 0.1})`;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }

        // 添加少量干扰点
        for (let i = 0; i < 15; i++) {
            ctx.fillStyle = `rgba(59, 130, 246, ${0.05 + Math.random() * 0.1})`;
            ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 1, 1);
        }

        // 绘制文字
        ctx.font = 'bold 20px Arial, sans-serif';
        ctx.textBaseline = 'middle';
        
        for (let i = 0; i < text.length; i++) {
            const x = 15 + i * 22;
            const y = canvas.height / 2 + (Math.random() - 0.5) * 4;
            
            const angle = (Math.random() - 0.5) * 0.2;
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(angle);
            
            const colors = ['#1e40af', '#3b82f6', '#1d4ed8', '#2563eb'];
            ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
            ctx.fillText(text[i], 0, 0);
            ctx.restore();
        }
    };

    // 生成验证码
    const generateCaptcha = () => {
        setCaptchaLoading(true);
        setCaptchaInput('');
        
        setTimeout(() => {
            const newCaptcha = generateRandomCaptcha();
            setCaptcha(newCaptcha);
            drawCaptcha(newCaptcha);
            setCaptchaLoading(false);
        }, 200);
    };

    // 验证验证码
    const validateCaptcha = (input: string) => {
        if (!captcha) return false;
        return input.toLowerCase() === captcha.toLowerCase();
    };

    // 处理输入变化
    const handleInputChange = (field: string, value: string) => {
        form.setFieldsValue({ [field]: value });
        // 验证码实时验证
        if (field === 'captcha') {
            if (value.length === 4) {
                if (validateCaptcha(value)) {
                    const captchaInput = document.querySelector('input[placeholder="' + t('register.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                    if (captchaInput) {
                        captchaInput.style.borderColor = '#10b981';
                        captchaInput.style.boxShadow = '0 0 0 3px rgba(16, 185, 129, 0.1)';
                    }
                } else {
                    const captchaInput = document.querySelector('input[placeholder="' + t('register.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                    if (captchaInput) {
                        captchaInput.style.borderColor = '#ef4444';
                        captchaInput.style.boxShadow = '0 0 0 3px rgba(239, 68, 68, 0.1)';
                    }
                }
            } else {
                const captchaInput = document.querySelector('input[placeholder="' + t('register.inputCaptchaPlaceholder') + '"]') as HTMLInputElement;
                if (captchaInput) {
                    captchaInput.style.borderColor = '#e5e7eb';
                    captchaInput.style.boxShadow = 'none';
                }
            }
        }
    };

    // 组件挂载时生成验证码
    useEffect(() => {
        generateCaptcha();
    }, []);

    // 注册表单提交逻辑
 const onFinish: FormProps<FieldType>['onFinish'] = async (values: FieldType) => {
    setLoading(true);
    console.log('onFinish called', values);
    try {
        // 验证验证码
        if (!validateCaptcha(values.captcha || '')) {
            message.error(t('register.captchaErrorMsg'));
            generateCaptcha();
            setLoading(false);
            return;
        }
        // 验证密码确认
        if (values.password !== values.confirmPassword) {
            message.error(t('register.passwordMismatch'));
            setLoading(false);
            return;
        }
        const res = await reg('/register', {
            username: values.username,
            password: values.password
        });
        console.log('注册响应:', res.data);
        const { code } = res.data
        if (code === 10000) {
            message.success(t('register.registerSuccess'));
            console.log('跳转login');
            nav('/login');
        } else {
            message.error(t('register.registerFail'));
            generateCaptcha();
        }
    } catch {
        message.error(t('register.registerErrorMsg'));
        generateCaptcha();
    } finally {
        setLoading(false);
    }
};

    // 注册按钮点击，先校验表单，再弹出人机验证弹窗
    const handleRegisterClick = () => {
        form.validateFields().then(values => {
            setPendingFormValues(values);
            setCaptchaModalVisible(true);
        }).catch(() => {});
    };

    // 人机验证通过后自动提交表单
    const handleCaptchaSuccess = () => {
        setCaptchaModalVisible(false);
        if (pendingFormValues) {
            onFinish(pendingFormValues);
            setPendingFormValues(null); // 注册后清空，防止多次触发
        }
    };

    return (
        <div className={style.registerContainer}>
            {/* 语言切换按钮 */}
            <div className={style.languageSwitch}>
                <Dropdown menu={{ items: languageItems }} placement="bottomRight">
                    <Button 
                        type="text" 
                        icon={<GlobalOutlined />}
                        className={style.languageButton}
                    >
                        {getCurrentLanguageText()}
                    </Button>
                </Dropdown>
            </div>

            {/* 左侧品牌区域 */}
            <div className={style.brandSection}>
                <div className={style.brandContent}>
                    <div className={style.brandTitle}>
                        <h1>{t('register.systemTitle')}</h1>
                        <h2>{t('register.systemSubtitle')}</h2>
                    </div>
                    
                    <div className={style.mainIllustration}>
                        <div className={style.documentIcon}>
                            <div className={style.documentContent}>
                                <div className={style.checkmark}>✓</div>
                                <div className={style.cross}>✗</div>
                                <div className={style.textLines}>
                                    <div className={style.line}></div>
                                    <div className={style.line}></div>
                                    <div className={style.line}></div>
                                </div>
                            </div>
                        </div>
                        <div className={style.illustrationRing}></div>
                    </div>
                    
                    <div className={style.cloud1}></div>
                    <div className={style.cloud2}></div>
                </div>
                
                {/* 背景装饰点 */}
                <div className={style.backgroundDots}></div>
            </div>

            {/* 右侧注册表单 */}
            <div className={style.formSection}>
                <div className={style.formContainer}>
                    <h2 className={style.formTitle}>{t('register.userRegister')}</h2>
                    <Form
                        form={form}
                        name="registerForm"
                        style={{ width: '100%' }}
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        autoComplete="off"
                        size="large"
                    >
                        <Form.Item
                            name="username"
                            rules={[
                                { required: true, message: t('register.inputUsername') },
                                { min: 3, message: t('register.usernameMinLength') },
                                { max: 20, message: t('register.usernameMaxLength') }
                            ]}
                        >
                            <Input 
                                prefix={<UserOutlined className={style.inputIcon} />} 
                                placeholder={t('register.inputAccount')}
                                className={style.customInput}
                            />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[
                                { required: true, message: t('register.inputPassword') },
                                { min: 6, message: t('register.passwordMinLength') },
                                { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: t('register.passwordPattern') }
                            ]}
                        >
                            <Input 
                                prefix={<LockOutlined className={style.inputIcon} />}
                                suffix={
                                    <Tooltip title={passwordVisible ? t('register.hidePassword') : t('register.showPassword')}>
                                        {passwordVisible ? (
                                            <EyeInvisibleOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setPasswordVisible(false)}
                                            />
                                        ) : (
                                            <EyeOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setPasswordVisible(true)}
                                            />
                                        )}
                                    </Tooltip>
                                }
                                type={passwordVisible ? 'text' : 'password'}
                                placeholder={t('register.inputPasswordPlaceholder')}
                                className={style.customInput}
                            />
                        </Form.Item>
                        <Form.Item
                            name="confirmPassword"
                            rules={[
                                { required: true, message: t('register.inputConfirmPassword') },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error(t('register.passwordMismatch')));
                                    },
                                }),
                            ]}
                        >
                            <Input 
                                prefix={<LockOutlined className={style.inputIcon} />}
                                suffix={
                                    <Tooltip title={confirmPasswordVisible ? t('register.hidePassword') : t('register.showPassword')}>
                                        {confirmPasswordVisible ? (
                                            <EyeInvisibleOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setConfirmPasswordVisible(false)}
                                            />
                                        ) : (
                                            <EyeOutlined 
                                                className={style.passwordToggle}
                                                onClick={() => setConfirmPasswordVisible(true)}
                                            />
                                        )}
                                    </Tooltip>
                                }
                                type={confirmPasswordVisible ? 'text' : 'password'}
                                placeholder={t('register.inputConfirmPasswordPlaceholder')}
                                className={style.customInput}
                            />
                        </Form.Item>
                        <Form.Item
                            name="captcha"
                            rules={[{ required: true, message: t('register.inputCaptcha') }]}
                            extra={
                                <div style={{
                                    fontSize: '12px',
                                    color: '#6b7280',
                                    marginTop: '4px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px'
                                }}>
                                    <span>💡</span>
                                    <span>{t('register.captchaTip')}</span>
                                </div>
                            }
                        >
                            <Row gutter={12}>
                                <Col span={14}>
                                    <Input 
                                        prefix={<SafetyOutlined className={style.inputIcon} />}
                                        placeholder={t('register.inputCaptchaPlaceholder')}
                                        value={captchaInput}
                                        onChange={(e) => {
                                            setCaptchaInput(e.target.value);
                                            handleInputChange('captcha', e.target.value);
                                        }}
                                        className={style.customInput}
                                        maxLength={4}
                                    />
                                </Col>
                                <Col span={10}>
                                    <div className={style.captchaContainer}>
                                        <canvas 
                                            ref={canvasRef}
                                            className={style.captchaCanvas}
                                            onClick={generateCaptcha}
                                            title={t('register.clickToRefresh')}
                                        />
                                        <Button 
                                            type="text"
                                            icon={<ReloadOutlined spin={captchaLoading} />}
                                            onClick={generateCaptcha}
                                            className={style.refreshButton}
                                            title={t('register.refreshCaptcha')}
                                        />
                                    </div>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                         rules={[{ required: true, message: t('register.inputCaptcha') }]}
                        >
                            <Button 
                                type="primary" 
                                loading={loading}
                                className={style.registerButton}
                                onClick={handleRegisterClick}
                            >
                                {loading ? t('register.registerLoading') : t('register.register')}
                            </Button>
                        </Form.Item>
                    </Form>
                    <Modal
                        open={captchaModalVisible}
                        footer={null}
                        onCancel={() => setCaptchaModalVisible(false)}
                        destroyOnClose
                        centered
                    >
                        <CaptchaVerification
                            onSuccess={handleCaptchaSuccess}
                            onFail={() => setCaptchaModalVisible(false)}
                            type="slider"
                            difficulty="medium"
                        />
                    </Modal>
                    <div className={style.loginLink}>
                        {t('register.alreadyHaveAccount')} 
                        <a onClick={() => nav('/login')} className={style.linkText}>
                            {t('register.goToLogin')}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Index
